<template>
  <div class="home-container">
    <div class="btn-top">
      <el-button class="btn-white" @click="back">返回</el-button>
      <el-button
        class="btn-blue"
        type="primary"
        @click="goodsId === 0 ?submitAddGoodsForm('addGoodsref'):submitEditGoodsForm('addGoodsref')"
        >提交</el-button
      >
    </div>
    <el-card class="add_goods_container">
      <div class="public-title-1">商品基本信息</div>
      <el-form
        label-width="80px"
        :rules="addGoodsFormRules"
        ref="addGoodsref"
        :model="addGoodsForm"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="商品型号">
              <el-input v-model="addGoodsForm.model"></el-input>
            </el-form-item>
            <el-form-item label="商品数量">
              <el-input v-model="addGoodsForm.number"></el-input>
            </el-form-item>
            <el-form-item label="所属分类">
              <el-input v-model="addGoodsForm.category"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8"
            ><el-form-item label="商品名称">
              <el-input v-model="addGoodsForm.goodName"></el-input>
            </el-form-item>
            <el-form-item label="商品单价">
              <el-input v-model="addGoodsForm.price"></el-input>
            </el-form-item>
            <el-form-item label="进货渠道">
              <el-radio-group
                v-model="addGoodsForm.resource"
                @change="changeHandler"
              >
                <el-radio :label="1">线上</el-radio>
                <el-radio :label="2">线下</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="品牌">
              <el-input v-model="addGoodsForm.brand"></el-input>
            </el-form-item>
            <el-form-item label="入库时间">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="addGoodsForm.putInTime"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="店铺名称" v-if="ShowFlag">
              <el-select v-model="addGoodsForm.shopId" placeholder="请选择">
                <el-option
                  v-for="item in shops"
                  :key="item.id"
                  :label="item.shopName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="!ShowFlag">
          <div class="public-title-1">店铺信息</div>
          <el-form-item label="店铺名称">
            <el-select v-model="addGoodsForm.shopId" placeholder="请选择">
                <el-option
                  v-for="item in shops"
                  :key="item.id"
                  :label="item.shopName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="店铺地址">
            <el-input v-model="addGoodsForm.shopLocation"></el-input>
          </el-form-item>
          <div class="map-box">
            <div class="public-map">
              <div id="container" class="public-map-container"></div>
              <!-- 地图-搜索框 -->
              <div class="public-map-search hide">
                <input
                  type="text"
                  placeholder="请输入搜索关键字"
                  autocomplete="off"
                  id="map_search_input"
                />
              </div>
            </div>
          </div>
        </div>
      </el-form>

      <div class="public-title-1">商品图片</div>
      <div class="img-container">
        <viewer :images="fileList">
          <img
            v-for="(src, index) in fileList"
            :src="`http://127.0.0.1:3007/${src}`"
            :key="index"
            class="img"
          />
        </viewer>
        <el-upload
          action="http://127.0.0.1:3007/goods/uploadImg"
          :before-upload="beforeAvatarUpload"
          :show-file-list="false"
          list-type="picture-card"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </div>
    </el-card>
  </div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader'
// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: '3d09a1323b24f3bce41709732387cb87'
}
export default {
  data () {
    return {
      addGoodsForm: {
        goodName: '',
        number: '',
        brand: '',
        model: '',
        price: '',
        putInTime: '',
        resource: 2,
        shopId: '',
        category: '',
        shopLocation: '',
        shopLng: '',
        shopLat: '',
        id: 0
      },
      ShowFlag: false,
      brands: [],
      fileList: [],
      fileIdList: [],
      map: '',
      goodsId: 0,
      marker: '',
      shops: [],
      addGoodsFormRules: {
        model: [
          {
            required: true,
            message: '请输入商品型号',
            trigger: 'blur'
          }
        ],
        number: [
          {
            required: true,
            message: '请输入商品数量',
            trigger: 'blur'
          }
        ],
        goodName: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入商品单价',
            trigger: 'blur'
          }
        ]
        // roleId: [{
        //   required: true,
        //   message: '请选择角色',
        //   trigger: 'blur'
        // }]
      }
    }
  },
  created () {
    // this.getBrands()

  },
  mounted () {
    // DOM初始化完成进行地图初始化

    this.getDetail()
    this.getShops()
  },
  computed: {},
  methods: {
    async getBrands () {
      const { data: res } = await this.$http.get('/goods/brand')
      if (res.code !== 200) {
        return this.$message.error(res.msg)
      }
      this.brands = res.data
    },
    async getShops () {
      const { data: res } = await this.$http.post('/goods/getShop')
      if (res.code !== 200) return this.$message.error(res.msg)
      this.shops = res.data
    },
    // 监听单选框选值变化
    changeHandler (value) {
      if (value === 1) {
        this.ShowFlag = true
      } else {
        this.ShowFlag = false
        this.initMap()
      }
    },
    initMap (lng, lat) {
      const that = this
      AMapLoader.load({
        key: 'bd0b90a131c9ea8ed6538fe0af1a0241',
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          'AMap.Scale',
          'AMap.ToolBar',
          'AMap.Geocoder',
          'AMap.PlaceSearch',
          'AMap.Autocomplete'
        ] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          // 初始化地图
          that.map = new AMap.Map('container', {
            viewMode: '2D', //  是否为3D地图模式
            zoom: 13, // 初始化地图级别
            center: [113.65553, 34.748764], // 中心点坐标  郑州
            resizeEnable: true
          })
          that.marker = new AMap.Marker({
            icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
            position: [lng !== undefined ? lng : '', lat !== undefined ? lat : ''],
            offset: new AMap.Pixel(-40, -50)
          })
          that.marker.setMap(that.map)
          lng !== undefined ? that.map.setCenter([lng, lat]) : that.marker.hide()
          var geocoder = new AMap.Geocoder()
          function regeoCode (markert, mapt, lnglat) {
            markert.setPosition(lnglat)
            that.addGoodsForm.shopLat = lnglat.lat
            that.addGoodsForm.shopLng = lnglat.lng
            mapt.setCenter(lnglat)
            geocoder.getAddress(lnglat, function (status, result) {
              if (status === 'complete' && result.regeocode) {
                var address = result.regeocode.formattedAddress
                that.addGoodsForm.shopLocation = address
              } else {
                console.log('根据经纬度查询地址失败')
              }
            })
          }
          // 点击事件
          that.map.on('click', function (e) {
            that.marker.show()
            regeoCode(that.marker, that.map, e.lnglat)
            that.map.add(that.marker)
          })
        })
        .catch((e) => {
          console.log(e)
        })
    },
    handleSuccess (res, file) {
      if (res.code !== 200) {
        return this.$alert.$message.error('上传图片失败！')
      }
      this.fileIdList.push(res.data.id)
      this.fileList.push(res.data.url)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    back () {
      this.$router.push('/goods')
    },
    async submitAddGoodsForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 解构赋值 await async化简promise
          const param = this.addGoodsForm
          console.log(this.fileIdList)
          param.fileId = this.fileIdList.join(',')
          const { data: res } = await this.$http.post('/goods/add', param)
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          this.$message.success('新增商品成功！')
          setTimeout(() => {
            this.$router.push('/goods')
          }, 3000)
        }
      })
    },
    async submitEditGoodsForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 解构赋值 await async化简promise
          const param = this.addGoodsForm
          param.fileId = this.fileIdList.join(',')
          const { data: res } = await this.$http.post('/goods/updateGoods', param)
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          this.$message.success('编辑商品成功！')
          setTimeout(() => {
            this.$router.push('/goods')
          }, 3000)
        }
      })
    },
    getDetail () {
      this.$refs.addGoodsref.resetFields()
      if (this.$route.query.id) {
        this.$nextTick(async () => {
          const { data: res } = await this.$http.post('/goods/search', {
            id: this.$route.query.id
          })
          this.goodsId = this.$route.query.id
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          this.addGoodsForm = res.data
          if (res.data.resource === 1) {
            this.ShowFlag = true
          } else {
            this.ShowFlag = false
            this.initMap(res.data.shoplng, res.data.shoplat)
            // this.marker.setPosition([res.data.shopLng, res.data.shopLat])
            // this.marker.show()
            // this.map.setCenter(this.marker)
          }
          for (let i = 0; i < res.data.url.length; i++) {
            this.fileList.push(res.data.url[i].picName)
          }
          // this.fileList = res.data.url !== undefined ? res.data.url.split(',') : []
          this.fileIdList =
            res.data.id !== undefined ? res.data.fileId.split(',') : []
        })
      } else {
        this.initMap()
      }
    }
  }
}
</script>
<style lang="less" scoped>
.home-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  .btn-top {
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
  .add_goods_container {
    height: calc(100% - 60px);
    overflow-y: auto;
    .brands {
      width: 100%;
    }
  } // 地图盒子
  .map-box {
    height: 369px;
    width: 100%;
    position: relative;
    margin-bottom: 20px;

    // 地图
    .public-map {
      width: 100%;
      height: 100%;
    }
  }

  .img-container {
    display: flex;
    .img {
      margin-right: 10px;
    }
  }
}
.img {
  width: 146px;
  height: 146px;
}
</style>
